package zdc.display {
import com.greensock.loading.ImageLoader;
import com.greensock.loading.LoaderMax;
import com.greensock.loading.SWFLoader;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.clearTimeout;
import flash.utils.getDefinitionByName;
import flash.utils.setTimeout;

import org.tuio.TuioTouchEvent;

import zdc.ui.MovingInertia;
import zdc.Util;

/**
 *
 * @author Simple Slime
 */
public class MultipleImagesWander extends MovieClip {
    public static const LOAD_COMPLETE:String = "MultipleImagesWander_LOAD_COMPLETE";

    private var idx:int = 1;
    private var mloader:LoaderMax;
    private var connNum:int = 1;
    private var okFun:Function = null;
    private var progFun:Function = null;
    private var swfs:Vector.<MovieClip> = new Vector.<MovieClip>();
    private var frames:Array;
    ;
    private var paths:Array;
    private var recur:Boolean = false;
    private var frameCount:int = 0;

    private var prev:DisplayObject;
    private var gest:DisplayObject;
    private var autoload:Boolean = true;
    private var loadingDio:ILoadingDio;

    private var complete:Boolean = false;
    private var delayLoad:Number = 0.5;
    private var timeout:int;
    protected var walkDist:Number = 8;
    protected var isWalk:Boolean = false;

    public function MultipleImagesWander(paths:Array = null, prev:DisplayObject = null, gest:DisplayObject = null, autoload:Boolean = true, loadingDio:ILoadingDio = null, delayLoad:Number = 0, recur:Boolean = false) {
        this.paths = paths;
        this.autoload = autoload;
        this.loadingDio = loadingDio;
        this.delayLoad = delayLoad;
        this.recur = recur;

        this.prev = prev;
        this.gest = gest;
        if (prev) {
            addChild(prev);
        }
        if (gest) {
            addChild(gest);
            gest.visible = false;
        }
        if (loadingDio) {
            loadingDio.reset();
        }

        initPreVars();
        stage ? init() : addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        initPostVars();
        initStates();
        initEvents();
        run();
    }

    private function initPreVars():void {
        mloader = new LoaderMax({
            onComplete: onOk,
            onProgress: onProg,
            maxConnections: connNum
        });
    }

    private function initPostVars():void {
        var mi:MovingInertia = new MovingInertia(this, null, TuioTouchEvent.TOUCH_DOWN, TuioTouchEvent.TOUCH_UP, TuioTouchEvent.TOUCH_MOVE, TuioTouchEvent.ROLL_OUT);
        if(isWalk){
            mi.addWalkHook(onMove);
            mi.WALK_TYPE = true;
            mi.minWalkDistX = walkDist;
        }
        else{
            mi.addMoveHook(onMove);
        }

        mi.enable = true;
    }

    private function initStates():void {

    }

    private function initEvents():void {
        addEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
    }

    private function run():void {
        //Helper.initTuio(this, false, false);
        //Util.fullScreen(stage);
        clearTimeout(timeout);
        if (autoload) {
            if (delayLoad) {						//trace("delayLoad!");
                timeout = setTimeout(load, delayLoad * 1000);
            }
            else {
                load();
            }
        }
    }

    /**
     * 加载资源
     * @param    paths
     */
    public function load(paths:Array = null):void {
        if (loadingDio) {
            loadingDio.reset();
        }

        this.paths = paths ? paths : this.paths;


        //删除上次的资源
        var i:int = 0;
        for (i = 0; i < swfs.length; i++) {
            this.removeChild(swfs[i]);
        }
        swfs = new Vector.<MovieClip>();
        frames = [];
        idx = 1;

        for (i = 0; i < this.paths.length; i++) {
            mloader.append(new SWFLoader(this.paths[i]));
        }

        mloader.load();
    }

    //清楚loader
    private function clearLoader():void {
        if (mloader) {
            mloader.dispose(true);
            //停止加载
            mloader.unload();
            mloader.empty();
        }
    }

    //加载进度
    private function onProg(e:Event):void {
        if (progFun != null) {
            progFun(mloader.bytesLoaded, mloader.bytesTotal);
        }
        if (loadingDio) {
            loadingDio.displayProgress(mloader.bytesLoaded, mloader.bytesTotal);
        }
    }

    //加载完毕
    private function onOk(e:Event):void {
        complete = true;
        var lastNum:int = 1;
        for (var i:int = 0; i < mloader.numChildren; i++) {
            var c:MovieClip = (mloader.getChildAt(i) as SWFLoader).rawContent as MovieClip;
            swfs.push(c);
            c.gotoAndStop(1);
            //c.visible = false;
            addChild(c);
            frameCount += c.totalFrames;
            frames.push(lastNum);
            lastNum += c.totalFrames;
        }

        if (gest) {
            gest.visible = true;
        }
        if (prev) {
            prev.visible = false;
        }

        Util.top(swfs[0]);
        gest && Util.top(gest);
        if (okFun != null) {
            okFun();
        }
        //显示进度条的的表现方式
        if (loadingDio) {
            loadingDio.displayCompletion();
        }
    }

    private function onMove(e:Event, dx:Number, dy:Number):void {
        if (!complete) {
            return;
        }

        if (dx < 0) {
            if (idx == 1) {
                idx = recur ? frameCount : idx;
            }
            else {
                idx--;
            }
        }
        else if (dx > 0) {
            if (idx == frameCount) {
                idx = recur ? 1 : idx;
            }
            else {
                idx++;
            }
        }
        hideOther();
        var n:int = Util.inNumPart(frames, idx);
        var swf:MovieClip = swfs[n];
        Util.top(swf);
        gest && Util.top(gest);
        //swf.visible = true;
        swf.gotoAndStop(idx - frames[n] + 1);		//trace("onMove:", idx, n, frameCount);
    }

    private function onRemoved(e:Event):void {
        removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
        clearTimeout(timeout);
        loadingDio = null;
        prev = null;
        gest = null;
        clearLoader();
    }

    /**
     * 隐藏其他对象
     */
    private function hideOther():void {
        for (var i:int = 0; i < swfs.length; i++) {
        }
    }

    /**
     * 最大同时连接数
     */
    public function get mxconnNum():int {
        return connNum;
    }

    public function set mxconnNum(value:int):void {
        connNum = value;
        mloader.maxConnections = value;
    }

    public function get loader():LoaderMax {
        return mloader;
    }

    /**
     * 加载完毕执行的函数
     */
    public function get onComplete():Function {
        return okFun;
    }

    public function set onComplete(value:Function):void {
        okFun = value;
    }

    /**
     * 加载过程函数    progFun(mloader.bytesLoaded, mloader.bytesTotal);
     */
    public function get onProgress():Function {
        return progFun
    }

    public function set onProgress(value:Function):void {
        progFun = value;
    }

    public function get walkDistance():Number{
        return walkDist;
    }

    public function set walkDistance(value:Number):void{
        walkDist = value;
    }
}

}